/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Enumeration;
import javax.ejb.EJB;
import javax.faces.FacesException;
import javax.faces.FactoryFinder;
import javax.faces.application.NavigationCase;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.webapp.FacesServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpa.entities.ItemPedido;
import jpa.entities.ItemPedidoPK;
import jpa.entities.Pedido;
import jpa.entities.Produto;
import jpa.entities.Usuario;
import jpa.session.ItemPedidoFacade;
import jpa.session.PedidoFacade;
import jpa.session.ProdutoFacade;
import jpa.session.UsuarioFacade;
import org.omg.PortableServer.REQUEST_PROCESSING_POLICY_ID;

/**
 *
 * @author carlos
 */
@WebServlet(name = "controleEstoque", urlPatterns = {"/controleEstoque"})
@ManagedBean(name = "controleEstoque")
@SessionScoped
public class controleEstoque extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @EJB
    private jpa.session.ItemPedidoFacade ejbItemPedidoFacade;
    @EJB
    private jpa.session.PedidoFacade ejbPedidoFacade;
    @EJB
    private jpa.session.ProdutoFacade ejbProdutoFacade;
    @EJB
    private jpa.session.UsuarioFacade ejbUsuarioFacade;
    private UserManager login = null;
    private Usuario user = null;
    private BuyManager compras;
    private ServletContext context;
    private Lifecycle lifecycle;
    private ServletConfig servletConfig;
    private FacesContextFactory facesContextFactory;
    private FacesContext facesContext;

    private ItemPedidoFacade getItemPedidoFacade() {
        return ejbItemPedidoFacade;
    }

    private PedidoFacade getPedidoFacade() {
        return ejbPedidoFacade;
    }

    private ProdutoFacade getProdutoFacade() {
        return ejbProdutoFacade;
    }

    private UsuarioFacade getUsuarioFacade() {
        return ejbUsuarioFacade;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {

        super.init(config);
        servletConfig = config;
        try {

            context = getServletContext();
            facesContextFactory =
                    (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
        } catch (FacesException e) {
            Throwable rootCause = e.getCause();

            if (rootCause == null) {
                throw e;
            } else {
                throw new ServletException(e.getMessage(), rootCause);
            }
        }

        try {

            LifecycleFactory lifecycleFactory =
                    (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
            String lifecycleId =
                    config.getServletContext().getInitParameter(FacesServlet.LIFECYCLE_ID_ATTR);

            if (lifecycleId == null) {
                lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE;
            }

            lifecycle = lifecycleFactory.getLifecycle(lifecycleId);


        } catch (FacesException e) {
            Throwable rootCause = e.getCause();
            if (rootCause == null) {
                throw e;
            } else {
                throw new ServletException(e.getMessage(), rootCause);
            }
        }




    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet controleEstoque</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet controleEstoque at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       try {

           String teste = "oi";
                //o método GET indica que a requisição é o retorno do Checkout PagSeguro para o site vendedor.
                //no término do checkout o usuário é redirecionado para este bloco.
        
        } catch (Exception e) {
            e.toString();
        } finally {
            try {
            } catch (Exception e) {
                e.toString();
            }

        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            //o método POST indica que a requisição é o retorno da validação NPI.
                Enumeration<?> en = request.getParameterNames();
                String token = "cole aqui o token do vendedor";
                StringBuffer validaNPI = new StringBuffer("Comando=validar&Token=");
                validaNPI.append(token);

                while (en.hasMoreElements()) {
                    String paramName = (String) en.nextElement();
                    String paramValue = request.getParameter(paramName);
                    validaNPI.append("&");
                    validaNPI.append(paramName);
                    validaNPI.append("=");
                    validaNPI.append(paramValue);
                }

                URL u = new URL("https://pagseguro.uol.com.br/pagseguro-ws/checkout/NPI.jhtml");
                URLConnection uc = u.openConnection();
                uc.setDoOutput(true);
                uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                PrintWriter pw = new PrintWriter(uc.getOutputStream());
                pw.println(validaNPI.toString());
                pw.close();

                BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                String res = in.readLine();
                in.close();

                //Verifica se o status da transação está VERIFICADO
                String transacaoID = request.getParameter("TransacaoID");
                if (res.equals("VERIFICADO")) {
                    //o post foi validado
                } else if (res.equals("FALSO")) {
                    //o post nao foi validado
                } else {
                    //erro na integração com PagSeguro.
                }

        } catch (Exception e) {
            e.toString();
        } finally {
            try {
            } catch (Exception e) {
                e.toString();
            }

        }

    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
